package arrray;

/**
 * @author huangxianjin
 * @date 2025/8/18 23:25
 * @description "加油站"
 */
public class LC_134 {
    public static void main(String[] args) {
        new LC_134().canCompleteCircuit(new int[]{3, 3, 4}, new int[]{3, 4, 4});
    }

    public int canCompleteCircuit(int[] gas, int[] cost) {
        if (gas == null || cost == null || gas.length != cost.length) {
            return -1;
        }
        int n = gas.length;
        for (int i = 0; i < n; i++) {
            if (gas[i] > 0 && gas[i] >= cost[i]) {
                int total = 0;
                int count = 0;
                int start = i;
                total += gas[start]; //初始汽油[3,3,4] [3,4,4]
                while (total >= 0) {
                    if (total - cost[start] >= 0) {
                        total -= cost[start];
                        count++;
                        start = ++start % n;
                        total += gas[start];
                        if (count >= n) {
                            return i;
                        }
                    } else {
                        break;
                    }
                }

            }
        }

        return -1;
    }
}
